<template>
    <div class="system-role">
        <!--系统角色-->
        <Headline
                :headline1="$t('m.SystemManagement') + '  /  '"
                :headline2="$t('m.UserAdmin')"
        />
        <!-- 操作部分 -->
        <a-card style="width: 100%">
            <div class="search-role">
                <div class="search-new-delete">
                    <div>
                        <a-input-search
                                class="a-input"
                                :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                                v-model="uesrslist.key"
                                @search="userlistSearch"
                                style="width: 200px"
                        />
                    </div>
                    <a-button
                            type="primary"
                            icon="plus"
                            @click="createUser"
                            v-if="isTrue('sys:user:adduser')"
                    >{{ $t("m.NewUser") }}
                    </a-button
                    >
                </div>
                <div></div>
            </div>
            <!--列表 -->
            <div class="conter-table">
                <div id="components-table-demo-size">
                    <a-table
                            style="margin-top: 30px"
                            :rowKey="(r, i) => i.toString()"
                            :columns="columns"
                            :data-source="datas"
                            bordered
                            :pagination="false"
                    >
                        <div slot="chxeds" slot-scope="chxeds, doc, i">
                            <a-switch
                                    default-checked
                                    :disabled="!isTrue('sys:user:valid')"
                                    :checked="doc.status == 0 ? false : true"
                                    @change="userchxed(chxeds, doc, i)"
                            />
                        </div>
                        <div class="btns" slot="tags" slot-scope="text, tags, i">
                            <a-button
                                    class="btn "
                                    type="primary"
                                    icon="edit"
                                    @click="changed(text, tags, i)"
                                    :disabled="!isTrue('sys:user:updateuser')"
                            >{{ $t("m.Modification") }}
                            </a-button
                            >
                            <a-button
                                    class="btn"
                                    type="danger"
                                    icon="delete"
                                    @click="usersdelete(text, tags, i)"
                                    :disabled="!isTrue('sys:user:deluser')"
                            >{{ $t("m.Delete") }}
                            </a-button
                            >
                            <a-popover class="hidepop" trigger="click">
                                <template slot="content">
                                    <a-button
                                            class="btn"
                                            type="primary"
                                            @click="userment(text, tags, i)"
                                    >{{ $t("m.TheNewAuthorization") }}
                                    </a-button
                                    >
                                    <a-button
                                            class="btn"
                                            type="primary"
                                            :disabled="!isTrue('sys:user:delrole')"
                                            @click="userLookAnth(text, tags, i)"
                                    >{{ $t("m.DeleteTheAuthorized") }}
                                    </a-button
                                    >
                                    <a-button
                                            class="btn"
                                            type="primary"
                                            :disabled="!isTrue('sys:user:reset')"
                                            @click="importEdit(text, tags, i)"
                                    >{{ $t("m.ResetPasswords") }}
                                    </a-button
                                    >
                                </template>
                                <a-button class="btn" type="primary" icon="bars">{{
                                    $t("m.More")
                                    }}
                                </a-button>
                            </a-popover>
                        </div>
                    </a-table>
                </div>
            </div>
        </a-card>
        <Drawer ref="drawer"></Drawer>
        <Delete ref="delete" :dalete="huadalete" @confirm="deleteOk"></Delete>
        <Modal :modal="usermodal" @modalLast="userAddOk" @modalhand="userchange">
            <a-form-model
                    ref="ruleForm"
                    :model="userform"
                    :rules="rules"
                    :label-col="{ span: 3 }"
                    :wrapper-col="{ span: 12 }"
            >
                <a-form-model-item :label="$t('m.UserType')">
                    <a-select
                            class="select-a"
                            v-model="userform.userType"
                            :options="userTypeList"
                            @change="handleSelectChange"
                    >
                    </a-select>
                </a-form-model-item>
                <a-form-model-item :label="$t('m.SystemAccount')" prop="userCode">
                    <a-input autocomplete="off" v-model="userform.userCode"></a-input>
                </a-form-model-item>
                <a-form-model-item :label="$t('m.SystemPassword')" prop="password">
                    <a-input
                            autoComplete="new-password"
                            type="password"
                            v-model="userform.password"
                            :disabled="disableds"
                    >
                    </a-input>
                </a-form-model-item>
                <a-form-model-item :label="$t('m.BindPersonnel')">
                    <a-input-search
                            :enter-button="$t('m.SelectPersonnel')"
                            size="default"
                            @search="userSearch"
                            v-model="idtext"
                            :disabled="disableds"
                    />
                </a-form-model-item>
                <a-form-model-item :label="$t('m.Nickname')" prop="nickname">
                    <a-input v-model="userform.nickname"></a-input>
                </a-form-model-item>
                <a-form-model-item :label="$t('m.IsEnabled')">
                    <a-select v-model="userform.status">
                        <a-select-option value="1"> 有效</a-select-option>
                        <a-select-option value="0"> 无效</a-select-option>
                    </a-select>
                </a-form-model-item>
            </a-form-model>
        </Modal>
        <Modal :modal="usersmodal" @modalLast="userIdOk" @modalhand="userschange">
            <div class="search-a ov_flex">
                <a-input-search
                        :placeholder="$t('m.PleaseEnterYourSearchTerms')"
                        size="large"
                        @search="authSearch"
                        v-model="formlists.key"
                />
            </div>
            <div id="components-table-demo-size">
                <a-table
                        :rowKey="(record) => record.id"
                        :columns="opkeys"
                        :data-source="opdata"
                        bordered
                        :pagination="false"
                        :row-selection="{
            onChange: onSelectChange,
            type: 'radio',
          }"
                >
                </a-table>
                <a-pagination
                        class="pages"
                        show-size-changer
                        :default-current="1"
                        :total="total"
                        @change="userPages"
                        :pageSizeOptions="['5', '10', '30', '40']"
                        @showSizeChange="useronShowSizeChange"
                />
            </div>
        </Modal>

        <Modal :modal="authmodal" @modalLast="authOk" @modalhand="authchange">
            <a-alert
                    :message="$t('m.SelectSystemRolesToAddFeatures')"
                    type="warning"
                    banner
                    closable
            />
            <div class="ov_flex">
                <span>{{ $t("m.SelectSystemRoles") }} :&nbsp;</span>
                <a-select
                        class="select-a"
                        v-model="rolelist.roleId"
                        @change="roleleSelectChange"
                >
                    <a-select-option
                            :value="item.roleId"
                            v-for="item in sletlerole"
                            :key="item.menuId"
                    >
                        {{ item.roleName }}
                    </a-select-option>
                </a-select>
            </div>
            <div class="ov_flex">
                <div>{{ $t("m.SelectFunctionMenu") }} :</div>
                <div v-if="treerole.length !== 0">
                    <a-tree :tree-data="treerole" @select="selectlist">
                        <template #title="{ key: treeKey, menuName }">
                            <a-dropdown :trigger="['contextmenu']">
                                <span>{{ menuName }}</span>
                                <template #overlay>
                                    <a-menu
                                            @click="
                      ({ key: id }) => onContextMenuClick(treeKey, menuKey)
                    "
                                    >
                                        <a-menu-item key="1">1st menu item</a-menu-item>
                                        <a-menu-item key="2">2nd menu item</a-menu-item>
                                        <a-menu-item key="3">3rd menu item</a-menu-item>
                                    </a-menu>
                                </template>
                            </a-dropdown>
                        </template>
                    </a-tree>
                </div>
                <a-empty v-else/>
            </div>
        </Modal>
        <Modal
                :modal="passwordmodal"
                @modalLast="passwordOk"
                @modalhand="passwordchange"
        >
            <div class="password-flex">
                <a-form-item
                        :label="$t('m.NewPassword')"
                        style="margin-top: 0px; margin-bottom: 0px"
                >
                    <a-input v-model="passfrom.password"></a-input>
                </a-form-item>
            </div>
        </Modal>
        <Modal :modal="lookmodal" @modalLast="lookOk" @modalhand="lookchange">
            <a-table
                    :rowKey="(r, i) => r.roleId"
                    :columns="columnlist"
                    :data-source="listids"
                    bordered
                    :pagination="false"
                    :row-selection="{
          onChange: listSelectChange,
          type: 'radio',
          selectedRowKeys: setsclete,
        }"
            ></a-table>
        </Modal>
        <Delete ref="userdelete" :dalete="dalete" @confirm="userdelete"></Delete>
    </div>
</template>
<script>
    import Headline from "@/components/Headline";
    import Drawer from "@/components/Drawer";
    import Delete from "@/components/Delete";
    import Modal from "@/components/common/Modal";
    import {Setperms} from "@/assets/js/setperms";
    import {
        delRoleUser,
        getAddRoleUser,
        getDelSysUser,
        getonOffAccount,
        getResetPassword,
        getRoleByUserId,
        getRoleList,
        getRoleMenuTreeByRoleId,
        getsaveSysUser,
        getSysUserList,
    } from "@/api/User";
    import {getPersonInfo} from "@/api/perAges";

    export default {
        name: "Homeuser",
        components: {Headline, Drawer, Delete, Modal},
        data() {
            return {
                dalete: {
                    titles: this.$t("m.DeleteThePrompt"),
                    type: "exclamation-point",
                    text: this.$t("m.AreYouSureToDeleteThisData"),
                },
                huadalete: {
                    titles: this.$t("m.ChangeStatus"),
                    type: "exclamation-point",
                    text: this.$t("m.AreYouSureToChangeuserStatus"),
                },
                columnlist: [
                    {
                        title: this.$t("m.CharacterName"),
                        dataIndex: "roleName",
                    },
                ],
                visiblelow: false,
                datas: [],
                usermodal: {
                    visible: false,
                    width: "700px",
                    title: this.$t("m.NewUser"),
                },
                usersmodal: {
                    visible: false,
                    width: "1000px",
                },
                authmodal: {
                    visible: false,
                    width: "600px",
                    title: this.$t("m.SystemUserAuthorization"),
                },
                passwordmodal: {
                    visible: false,
                    width: "300px",
                    title: this.$t("m.ResetPasswords"),
                },
                lookmodal: {
                    visible: false,
                    width: "500px",
                    title: this.$t("m.DeleteTheAuthorized"),
                },
                columns: [
                    {
                        title: this.$t("m.SystemAccount"),
                        dataIndex: "userCode",
                    },
                    {
                        title: this.$t("m.Name"),
                        dataIndex: "nickname",
                    },
                    {
                        title: this.$t("m.UserType"),
                        dataIndex: "userTypeName",
                        width: '140px'
                    },
                    {
                        title: this.$t("m.LoginNumber"),
                        dataIndex: "loginTime",
                        width: "80px",
                    },
                    {
                        title: this.$t("m.LastLogin"),
                        dataIndex: "lastLoginDate",
                        width: "170px",
                    },
                    {
                        title: this.$t("m.LastLoginIP"),
                        dataIndex: "lastLoginIp",
                        width: "150px",
                    },
                    {
                        title: this.$t("m.RegistrationDate"),
                        dataIndex: "createDate",
                        width: '170px'
                    },
                    {
                        title: this.$t("m.Status"),
                        key: "chxeds",
                        dataIndex: "status",
                        scopedSlots: {customRender: "chxeds"},
                    },
                    {
                        title: this.$t("m.Operation"),
                        key: "tags",
                        dataIndex: "address",
                        scopedSlots: {customRender: "tags"},
                    },
                ],
                formRoleid: {
                    userId: "",
                    roleId: "",
                },
                loading: false,
                uesrslist: {
                    key: "",
                    start: 0,
                    limit: 30,
                },
                userform: {
                    userId: 0,
                    userCode: "",
                    password: "",
                    nickname: "",
                    empId: 0,
                    userType: "",
                    status: "",
                },
                formlists: {
                    ymOrgTreeCode: "",
                    infoType: 1,
                    status: "-1",
                    vChild: false,
                    key: "",
                    page: 1,
                    start: 0,
                    limit: 5,
                },
                opkeys: [
                    {
                        title: this.$t("m.jobnumber"),
                        dataIndex: "ymorgtreecode",
                    },
                    {
                        title: this.$t("m.Name"),
                        dataIndex: "stafforstuname",
                    },
                    {
                        title: this.$t("m.Sex"),
                        dataIndex: "sex",
                    },
                    {
                        title: this.$t("m.officialRank"),
                        dataIndex: "infotype",
                    },
                    {
                        title: this.$t("m.coherentUnits"),
                        dataIndex: "orgname",
                    },
                ],
                replaceFields: {
                    title: "menuName",
                    key: "menuId",
                    children: "children",
                },
                rules: {
                    userCode: [
                        {
                            required: true,
                            message: this.$t("m.RulesMessage"),
                            trigger: "change",
                        },
                    ],
                    password: [
                        {
                            required: true,
                            message: this.$t("m.RulesMessage"),
                            trigger: "change",
                        },
                    ],
                    nickname: [
                        {
                            required: true,
                            message: this.$t("m.RulesMessage"),
                            trigger: "change",
                        },
                    ],
                },
                msg: "",
                message: "",
                opdata: [],
                //状态改变数据
                sliding: {
                    userId: "",
                    status: "",
                },
                passfrom: {
                    userId: "",
                    password: "",
                },
                authform: {
                    start: 0,
                    limit: 10,
                },
                roles: {
                    roleId: "",
                },
                disableds: false,
                usersId: "", //删除id
                idtext: "", //绑定用户名字
                total: 0,
                sletlerole: [],
                treerole: [],
                rolelist: {
                    roleId: "",
                    userId: "",
                },
                listids: [],
                setsclete: [],
                custlevel: '',
                userTypeList: [
                    {
                        value: '0',
                        label: '开发者',
                    },
                    {
                        value: '1',
                        label: '厂家',
                    },
                    {
                        value: '2',
                        label: '代理商',
                    },
                    {
                        value: '3',
                        label: '管理员',
                    },
                    {
                        value: '4',
                        label: '普通操作员'
                    }
                ]
            };
        },
        created() {
            this.custlevel = JSON.parse(localStorage.getItem("userinfo")).custlevel;
            this._getSysUserList(); //获取用户数据
            this.parms = Setperms(
                this.$route.fullPath,
                JSON.parse(sessionStorage.getItem("menu"))
            );
            if (this.custlevel != 0) {
                this.userTypeList = [
                    {
                        value: 3,
                        label: '管理员',
                    },
                    {
                        value: 4,
                        label: '普通操作员'
                    }
                ]
            }
        },
        methods: {
            isTrue(str) {
                return this.parms.indexOf(str) !== -1;
            },
            _getSysUserList() {
                getSysUserList({params: this.uesrslist}).then((res) => {
                    this.datas = res.data.data;
                    console.log(res);
                });
            },
            // 新建用户
            createUser() {
                this.msg = "新增用户成功";
                this.message = "修改用户成功";
                this.usermodal.title = this.$t("m.AddUser");
                this.rules.password[0].required = true;
                this.usermodal.visible = true;
                this.userform.userType = this.userTypeList[0].value;
                this.userform.userCode = "";
                this.userform.nickname = "";
                this.userform.status = "1";
                this.userform.password = "";
                this.userform.empId = 0;
                this.userform.userId = 0;
                this.disableds = false;
            },
            // 新建弹窗确定
            userAddOk() {
                this.$refs.ruleForm.validate((valid) => {
                    if (valid) {
                        getsaveSysUser(this.userform).then((res) => {
                            if (res.data.success) {
                                console.log(res);
                                this.$message.success(this.msg);
                                this._getSysUserList();
                            } else {
                                this.$message.error(this.message);
                            }
                        });
                        this.usermodal.visible = false;
                        this.idtext = "";
                    } else {
                        return false;
                    }
                });
            },
            //新增弹窗取消
            userchange() {
                this.userform.userType = this.userTypeList[0].value;
                this.userform.userCode = "";
                this.userform.nickname = "";
                this.userform.status = "";
                this.userform.password = "";
                this.userform.empId = "";
                this.userform.userId = 0;
                this.usermodal.visible = false;
                this.idtext = "";
                this.$refs.ruleForm.resetFields();
            },
            //新建弹窗select
            handleSelectChange(value, option) {
                console.log(value);
                console.log(option);
            },
            //更改状态 滑块点击
            userchxed(chxeds, doc, i) {
                this.sliding.userId = doc.userId;
                switch (doc.status) {
                    case 0:
                        this.sliding.status = 1;
                        break;
                    case 1:
                        this.sliding.status = 0;
                        break;
                }
                this.$refs.delete.visible = true;
            },
            userLookAnth(text, tags, i) {
                this.formRoleid.userId = tags.userId;
                const hide = document.getElementsByClassName("ant-popover-placement-top");
                hide[i].style.display = "none";
                getRoleByUserId({params: {userId: tags.userId}}).then((res) => {
                    this.listids = res.data.data;
                });
                this.lookmodal.visible = true;
            },
            lookOk() {
                if (this.setsclete.length > 0) {
                    delRoleUser(this.formRoleid).then((res) => {
                        const msg = res.data.msg;
                        if (res.data.success) {
                            this.$message.success("删除角色成功");
                            this.lookmodal.visible = false;
                            this.formRoleid.roleId = "";
                            this.formRoleid.userId = "";
                        } else {
                            this.$message.error("删除角色失败");
                        }
                    });
                } else {
                    this.$message.error("请选择角色");
                }
            },
            lookchange() {
                this.formRoleid.roleId = "";
                this.formRoleid.userId = "";
                this.setsclete = [];
            },
            listSelectChange(i, s) {
                console.log(i);
                this.setsclete = i;
                this.formRoleid.roleId = i[0];
            },
            //滑块弹窗确定
            deleteOk() {
                getonOffAccount(this.sliding)
                    .then((res) => {
                        if (res.data.success) {
                            this.$message.success("状态更新成功");
                            this._getSysUserList();
                        } else {
                            this.$message.error("状态更新失败");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                this.$refs.delete.visible = false;
            },
            //选择人员
            userSearch() {
                getPersonInfo({params: this.formlists}).then((res) => {
                    this.opdata = res.data.data;
                    this.total = res.data.total;
                });
                this.usersmodal.visible = true;
            },
            //搜索
            userlistSearch() {
                this._getSysUserList();
            },
            //修改按钮的点击
            changed(text, tags, i) {
                this.usermodal.title = "修改用户";
                this.msg = "修改用户成功";
                this.message = "修改用户失败";
                this.usermodal.visible = true;
                this.rules.password[0].required = false;
                console.log(tags);
                this.disableds = true;
                this.userform.userType = tags.userType;
                this.userform.userCode = tags.userCode;
                this.userform.nickname = tags.nickname;
                this.userform.status = tags.status + "";
                this.userform.password = tags.password;
                this.userform.empId = tags.empId;
                this.userform.userId = tags.userId;
            },
            //删除按钮的点击
            usersdelete(text, tags, i) {
                this.$refs.userdelete.visible = true;
                this.usersId = tags.userId;
            },
            //删除确定
            userdelete() {
                getDelSysUser({userId: this.usersId})
                    .then((res) => {
                        if (res.data.success) {
                            this.$message.success("删除成功");
                            this._getSysUserList();
                        } else {
                            this.$message.error("删除失败");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                this.$refs.userdelete.visible = false;
            },
            //查看授权
            userment(text, tags, i) {
                this.authmodal.visible = true;
                const hide = document.getElementsByClassName("ant-popover-placement-top");
                hide[i].style.display = "none";
                console.log(tags);
                this.rolelist.userId = tags.userId;
                getRoleList({params: this.authform}).then((res) => {
                    this.sletlerole = res.data.data;
                    console.log(res);
                });
            },
            //选择人员方法
            //搜索
            authSearch() {
            },
            onSelectChange(id, sleltext) {
                console.log(sleltext[0]);
                this.idtext = sleltext[0].stafforstuname;
                this.userform.empId = sleltext[0].id;
            },
            userIdOk() {
                this.usersmodal.visible = false;
            },
            userschange() {
                this.usersmodal.visible = false;
            },
            //分页
            useronShowSizeChange(page, limit) {
                this.formlists.page = page;
                this.formlists.limit = limit;
                this.formlists.start = (page - 1) * limit;
                getPersonInfo({params: this.formlists}).then((res) => {
                    this.opdata = res.data.data;
                });
            },
            userPages(page, pageSize) {
                this.formlists.page = page;
                this.formlists.limit = pageSize;
                this.formlists.start = (page - 1) * pageSize;
                getPersonInfo({params: this.formlists}).then((res) => {
                    this.opdata = res.data.data;
                });
            },
            //重置密码
            importEdit(text, tags, i) {
                const hide = document.getElementsByClassName("ant-popover-placement-top");
                console.log(hide);
                hide[i].style.display = "none";
                this.passfrom.userId = tags.userId;
                this.passwordmodal.visible = true;
            },
            passwordOk() {
                getResetPassword(this.passfrom)
                    .then((res) => {
                        if (res.data.success) {
                            this.$message.success("修改密码成功");
                        } else {
                            this.$message.error("修改密码失败");
                        }
                    })
                    .catch((err) => {
                        console.log(err);
                    });
                this.passfrom.password = "";
                this.passwordmodal.visible = false;
            },
            passwordchange() {
                this.passwordmodal.visible = false;
                this.passfrom.password = "";
            },

            //授权
            roleleSelectChange(i, s) {
                console.log(i, s);
                getRoleMenuTreeByRoleId({
                    params: {roleId: this.rolelist.roleId},
                }).then((res) => {
                    console.log(res.data);
                    this.treerole = res.data;
                });
            },
            //授权确定
            authOk() {
                if (this.rolelist.roleId == "") {
                    this.$message.error("请选择系统角色");
                } else {
                    getAddRoleUser(this.rolelist)
                        .then((res) => {
                            console.log(res);
                            const msg = res.data.msg;
                            if (res.data.success) {
                                this.$message.success("角色授权成功");
                            } else {
                                this.$message.error(msg);
                            }
                        })
                        .catch((err) => {
                            console.log(err);
                        });
                    this.authmodal.visible = false;
                }
            },
            authchange() {
            },
            //tree方法
            selectlist(selectedKeys, idNode) {
                const idNodes = idNode.selectedNodes[0].data.props.dataRef;
                console.log(idNodes);
                this.rolelist.roleId = idNodes.menuId;
            },
            onContextMenuClick(treeKey, menuKey) {
                console.log(`treeKey: ${treeKey}, menuKey: ${menuKey}`);
            },
        },
    };
</script>


<style scoped lang="scss">
    .system-role {
        width: 100%;
        height: 100%;
    }

    .search-role {
        width: 100%;
        // line-height: 60px;
    }

    .search-a {
        width: 300px;
        margin: 15px 0;
    }

    .search-new-delete {
        display: flex;
        align-items: center;
    }

    button {
        // margin-right: 10px;
    }

    .pages {
        margin: 15px 0;
    }

    .a-input {
        margin-right: 15px;
    }

    .select-a {
        width: 326px;
    }

    .ant-form-item {
        display: flex;
        margin-top: 20px;
        justify-content: center;
    }

    .ov_flex {
        display: flex;
        // justify-content: center;
        margin-left: 20px;
        margin-top: 20px;
        align-items: center;
    }

    .btn {
        margin-left: 15px;
        font-size: 10px;

    }

    /deep/ .ant-table-tbody > tr > td {
        padding: 15px 10px;
    }

    .conter-table {
        overflow: hidden;
        overflow-x: auto;
    }

    .btns {
        min-width: 200px;
    }
</style>
